unit ELogIn;

interface

uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
  Buttons, Mask, DB ,DBTables ,Dialogs ,ExtCtrls,
  inifiles, DBClient, FMTBcd, SqlExpr, Provider, IdBaseComponent,
  IdComponent, IdTCPConnection, IdTCPClient, Spin, jpeg,
  ZAbstractRODataset, ZAbstractDataset, ZDataset;

type
  TPasswordDlg = class(TForm)
    Image1: TImage;
    lblUsername: TLabel;
    lblPassword: TLabel;
    OKBtn: TBitBtn;
    CancelBtn: TBitBtn;
    edUsername: TEdit;
    edPassword: TEdit;
    IdTCPClient: TIdTCPClient;
    BitBtn1: TBitBtn;
    qrLogin: TZQuery;
    lblShowDB: TLabel;
    qrConfig: TZQuery;
    qrUpdSec: TZQuery;
    qrUpd_Config: TZQuery;
    qrUpd_Cnt_Sec: TZQuery;
    procedure OKBtnClick(Sender: TObject);
    procedure CancelBtnClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure edUsernameEnter(Sender: TObject);
    procedure edUsernameExit(Sender: TObject);
    procedure BitBtn1Click(Sender: TObject);
  private
    { Private declarations }
    Flogin :boolean;
  public
    { Public declarations }
    procedure Set2Ip(value:WideString);
    property LoginOk :boolean read FLogin write Flogin;
    //function LoginOk:boolean;
  end;

var
  PasswordDlg: TPasswordDlg;

implementation
uses dmIdocqment,Utility,EMain,ESetDatabaseIni,uEncrypt, UbinaryXor;

{$R *.dfm}
resourcestring sMyNewErrorMessage = 'User %s Not Sign In System ';
               sMyPwdErrorMessage = 'User %s Not Right In System ';
               sMyOrgErrorMessage = 'Organization %s Not Right In System ';
               
procedure TPasswordDlg.OKBtnClick(Sender: TObject);
var Userok,pwdOk ,chk_ok :boolean;
  strPwd:string;
  exIni :Tinifile;
  dbName_,dbPath_ :string;
  i,read_sec,read_tmp:integer;
  Author_,Lic_:string;

  chkGenDate:integer;
  Year, Month, Day: Word;
  tmpGen,chkRealVer:string;
  dt_:Tdatetime;
  iCfSum, iCcSum, iPosCc :integer;
  sRegCc, sMaxCon : string;
  Fcrc : TCRCCalculator;
begin
  with DM.cnDB do
  begin
    connected:=false;
  end  ;

  with qrLogin do
  begin
    if active then close;
    params[0].asstring:=trim(edUsername.text);
    open;
    userok:= recordcount > 0 ;
    //--check user sign in system
    if not userok then
    begin
      edUsername.setfocus;
      raise exception.createresfmt(@sMyNewErrorMessage, [edUsername.text]);
    end;
    //--check right
    //strPwd:= EnCodeLogin(fieldbyname('Passwrd').asstring,1);
    strPwd:= Encrypt(trim(edPassword.text),my_key);
    pwdOk:= strpwd = (fieldbyname('pwd').asstring);
    if not pwdOk then
    begin
      edPassword.setfocus;
      raise exception.createresfmt(@sMyPwdErrorMessage, [edUsername.text]);
    end;
  end;

  //-- Close Dialogs
  FLogin:=(userok and pwdok);
  if FLogin then
  begin
    exini:=TIniFile.create(ExtractFilePath(Application.ExeName)+'Emborider.ini' );
    with exini do
    begin
      Writestring('Login','User',edUsername.text);
      Writestring('Login','Date',formatdatetime('dd/mm/yyyy hh:mm:ss',now));
      //Writestring('Server','IP',edServer.text);
    end;
    exini.free;
    exini:=nil;
    ModalResult:=mrOK;
  end else
    Application.Terminate;

  (*
    with dm do
    begin
      users:=edUsername.text;
      //fmMain.StatusBarShow.Panels[2].text:=qrLogin.fieldbyname('name').asstring+' '+formatdatetime('dd/mm/yyyy hh:mm:ss',now);
      uid:=qrLogin.fieldbyname('id').asinteger;
      groups:=qrLogin.fieldbyname('dept').asstring;
      //fmMain.Timer1.Enabled:=true;
    end;
    close;
    qrConfig.close;
    qrConfig.open;
    read_sec:=qrConfig.fieldbyname('sec').asinteger;
    i:=qrConfig.fieldbyname('tec').asinteger;

    if qrConfig.fieldbyname('sec').isnull then read_tmp:=0
    else read_tmp:=read_sec;

    begin
      if uppercase(Extractfilename(Application.ExeName))='IDOCQMENTCOM.EXE' then
      begin
        Author_ := getSerialHD;
        chk_ok:=true;
      end else
      if (uppercase(Extractfilename(Application.ExeName))='IDOCQMENTDEMO.EXE')then
      begin
        Author_ := getSerialHD;
        chk_ok:=true;
      end else

      begin
        with IdTCPClient do
        begin
          try
            try
              Host := qrConfig.fieldbyname('serverip').asstring;
              Port := qrConfig.fieldbyname('port').asinteger;

              Connect;
              Writeln('LC');
              Author_ := ReadLn;
              Writeln('XX');
              chk_ok:=true;
            except on e:exception do
              begin
                chk_ok:=false;
                showmessage('Cannot connect license server ,please check server license is running-->'+e.message);
              end;
            end;
          finally
            Disconnect;
          end;
        end;
      end;

      if chk_ok then
      begin
        chkRealVer:=copy(qrConfig.fieldbyname('regno').asstring,1,1);
        {DecodeDate(qrConfig.fieldbyname('regen_date').asdatetime, Year, Month, Day);
        chkGenDate:=Year + Month + Day;
        tmpGen:=copy(intTostr(chkGenDate),2,3);}
        tmpGen:=copy(qrConfig.fieldbyname('regno').asstring, 2, 3);

        //--Check sum;
        iCfSum:=qrConfig.fieldbyname('tec').asinteger;
        //--Calculate sum;
        iPosCc:=pos('#', trim(qrConfig.fieldbyname('regno').asstring));
        sRegCc:=copy(trim(qrConfig.fieldbyname('regno').asstring), 1, iPosCc - 1);
        Fcrc := TCRCCalculator.create();
        iCcSum:=Fcrc.StringCRC16(sRegCc);
        Fcrc.free;
        Fcrc := nil;

        //--check correct license;
        if uppercase(Extractfilename(Application.ExeName))<>'IDOCQMENTDEMO.EXE' then
        begin
          if iCcSum <> iCfSum then
          begin
            showmessage('Invalid license key ,please call sumrantim@hotmail.com 08-1552-9248');
            Application.Terminate;
          end;
        end;

        //if (uppercase(Extractfilename(Application.ExeName))<>'IDOCQMENTCOM.EXE')and
          //(uppercase(Extractfilename(Application.ExeName))<>'IDOCQMENTDEMO.EXE')then
        if (uppercase(Extractfilename(Application.ExeName))= 'IDOCQMENT.EXE')then
        begin
          //--Show maximum license;
          with IdTCPClient do
          begin
            try
              try
                Host := qrConfig.fieldbyname('serverip').asstring;
                Port := qrConfig.fieldbyname('port').asinteger;

                Connect;
                Writeln('MX'+tmpGen);
              except on e:exception do
                begin
                  showmessage('Cannot connect license server ,please check server license is running-->'+e.message);
                end;
              end;
            finally
              Disconnect;
            end;
          end;
          //--check Maximum License;
          with IdTCPClient do
          begin
            try
              try
                Host := qrConfig.fieldbyname('serverip').asstring;
                Port := qrConfig.fieldbyname('port').asinteger;

                Connect;
                Writeln('CN');
                sMaxCon:=ReadLn;
                if strToint(sMaxCon) >= strToint(tmpGen) then
                begin
                  showmessage('Over connection of maximum license ,please call sumrantim@hotmail.com 08-1552-9248');
                  Application.Terminate;
                end;
              except on e:exception do
                begin
                  showmessage('Cannot connect license server ,please check server license is running-->'+e.message);
                end;
              end;
            finally
              Disconnect;
            end;
          end;
        end;

        if uppercase(Extractfilename(Application.ExeName))<>'IDOCQMENTDEMO.EXE' then
        begin
          if chkRealVer='A' then
          begin
            Lic_:=Generate2License(uppercase(chkRealVer + tmpGen +Encrypt(trim(Author_),my_key)));

            //if trim(Lic_)<> trim(qrConfig.fieldbyname('regno').asstring) then
            if trim(Lic_) <> sRegCc then
            begin
              showmessage('Invalid license key ,please call sumrantim@hotmail.com 08-1552-9248');
              Application.Terminate;
            end;
          end else
          begin
            Lic_:=Generate2License(uppercase(chkRealVer + tmpGen +Encrypt(trim(Author_),my_key)));

            //if trim(Lic_)<> trim(qrConfig.fieldbyname('regno').asstring) then
            if trim(Lic_) <> sRegCc then
            begin
              showmessage('Invalid license key ,please call sumrantim@hotmail.com 08-1552-9248');
              Application.Terminate;
            end else
            begin
              qrUpd_Config.parambyname('regen_date').asdatetime:=Date;
              qrUpd_Config.execsql;

              //qrUpd_Cnt_Sec.parambyname('regen_date').asdatetime:=Date;
              //qrUpd_Cnt_Sec.parambyname('regen').asdatetime:=Date;
              qrUpd_Cnt_Sec.ExecSql;

              //dt_:=qrConfig.fieldbyname('regen_date').asdatetime + 30;
              //if Date > dt_ then
              if qrConfig.fieldbyname('sec').asinteger > 200 then
              begin
                showmessage('Expire in license key for demo version ,please call sumrantim@hotmail.com 08-1552-9248');
                Application.Terminate;
              end;
            end;
          end;
        end else
        begin
          qrUpd_Config.parambyname('regen_date').asdatetime:=Date;
          qrUpd_Config.execsql;

          qrUpd_Cnt_Sec.ExecSql;

          if qrConfig.fieldbyname('sec').asinteger > 50 then
          begin
            showmessage('Expire in license key for demo version ,please call sumrantim@hotmail.com 08-1552-9248');
            Application.Terminate;
          end;
        end;
      end else Application.Terminate;
    end;
  end;
  *)
end;

procedure TPasswordDlg.CancelBtnClick(Sender: TObject);
begin
  Flogin:=false;
  close;
end;

procedure TPasswordDlg.FormShow(Sender: TObject);
var exIni :Tinifile;
begin
  exini:=TIniFile.create(ExtractFilePath(Application.ExeName)+'Emborider.ini' );
  with exini do
  begin
    edUsername.text:=readstring('Login','User','');
    //edServer.text:=readstring('Server','IP','127.0.0.1');
    lblShowDB.caption:=readstring('DB','HostName','127.0.0.1')+' - '+readstring('DB','Database','idocqment');
  end;
  exini.free;
  exini:=nil;
  //showmessage(uppercase(Extractfilename(Application.ExeName)));
  if uppercase(Extractfilename(Application.ExeName))='IDOCQMENTCOM.EXE' then
  begin
    BitBtn1.visible:=false;
    lblShowDB.visible:=false;
  end;
end;

procedure TPasswordDlg.Set2Ip(value: WideString);
begin

end;

procedure TPasswordDlg.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key=VK_Up then SelectNext(ActiveControl,false,true);
  if Key=VK_Down then SelectNext(ActiveControl,true,true);
end;

procedure TPasswordDlg.FormKeyPress(Sender: TObject; var Key: Char);
begin
  if Key=#13 then SelectNext(ActiveControl,true,true);
end;

procedure TPasswordDlg.edUsernameEnter(Sender: TObject);
begin
  SetBackColor(sender,true);
end;

procedure TPasswordDlg.edUsernameExit(Sender: TObject);
begin
  SetBackColor(sender,false);
end;

procedure TPasswordDlg.BitBtn1Click(Sender: TObject);
var fm:TfmSetDatabase;
  exIni :Tinifile;
begin
  fm:=TfmSetDatabase.create(self);
  try
    fm.showmodal;
  finally
    fm.Free;
    fm:=nil;
  end;
  exini:=TIniFile.create(ExtractFilePath(Application.ExeName)+'Emborider.ini' );
  with exini do
  begin
    lblShowDB.caption:=readstring('DB','HostName','127.0.0.1')+' - '+readstring('DB','Database','idocqment');
  end;
  exini.free;
  exini:=nil;
end;

end.

